package l2hc.gameserver.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

import l2hc.commons.dbutils.DbUtils;
import l2hc.commons.threading.RunnableImpl;
import l2hc.gameserver.ThreadPoolManager;
import l2hc.gameserver.database.DatabaseFactory;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SfDDenialDAO
{
   private static final Logger _log = LoggerFactory.getLogger(SfDDenialDAO.class);

   @SuppressWarnings({ "unchecked", "rawtypes" })
   private static ArrayList<String> _l = new ArrayList();

  public static void LoadAllIps()
  {
     Connection con = null;
     PreparedStatement statement = null;
     ResultSet rset = null;
    try
    {
       String ip = "";
       con = DatabaseFactory.getInstance().getConnection();
       statement = con.prepareStatement("SELECT * FROM ip_table");
       rset = statement.executeQuery();
      while (rset.next())
      {
         ip = rset.getString("ip");
         if (ip != "")
           _l.add(ip);
      }
    }
    catch (Exception e)
    {
       _log.info("ppc?");
    }
    finally
    {
       DbUtils.closeQuietly(con, statement, rset);
       _log.info("black list loaded size: " + _l.size() + "");
    }
  }

  public static void addBlackList(String ip)
  {
     _l.add(ip);
     _log.info("adding IP to black list " + ip + "");
  }

  public static ArrayList<String> getBlackList()
  {
     return _l;
  }

  public static void startSaveIP()
  {
     ThreadPoolManager.getInstance().scheduleAtFixedRate(new SaveIPs(), 60000L, 3600000L);
  }

  private static void delRecords()
  {
     Connection con = null;
     PreparedStatement statement = null;
    try
    {
       con = DatabaseFactory.getInstance().getConnection();
       statement = con.prepareStatement("DELETE FROM ip_table");
       statement.execute();
    }
    catch (Exception e)
    {
       _log.error("", e);
    }
    finally
    {
       DbUtils.closeQuietly(con, statement);
    }
     for (String _ip : _l)
    {
       saveIP(_ip);
    }
     _log.info("saved " + _l.size() + " ip in the block list");
  }

  public static void SaveIPs0()
  {
     delRecords();
  }

  public static void saveIP(String ip)
  {
     Connection con = null;
     PreparedStatement statement = null;
    try
    {
       con = DatabaseFactory.getInstance().getConnection();
       statement = con.prepareStatement("INSERT INTO ip_table (ip) VALUES(?)");
       statement.setString(1, ip);
       statement.execute();
    }
    catch (Exception e)
    {
    }
    finally
    {
       DbUtils.closeQuietly(con, statement);
    }
  }

  public static class SaveIPs extends RunnableImpl
  {
    public void runImpl()
      throws Exception
    {
       SfDDenialDAO.SaveIPs0();
    }
  }
}
